package com.cjbdi.websocket;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import com.cjbdi.dao.UserRepository;
import com.cjbdi.entity.UserInfo;
import com.cjbdi.util.IpUtil;


@Service
//访问服务端的url地址
@ServerEndpoint(value = "/websocket/{ip}")
public class WebSocketServer {
  static UserRepository userRepository; 
  @Autowired
  public void setRabbitAdmin(UserRepository userRepository){
    	WebSocketServer.userRepository = userRepository;
  }
  private static int onlineCount = 0;
  private static ConcurrentHashMap<String, WebSocketServer> webSocketSet = new ConcurrentHashMap<>();

  //与某个客户端的连接会话，需要通过它来给客户端发送数据
  private Session session;
  static final Logger log = LoggerFactory.getLogger(WebSocketServer.class);
  /**
   * 连接建立成功调用的方法*/
  @OnOpen
	public void onOpen(@PathParam(value = "ip") String ip, Session session) {
		this.session = session;
		webSocketSet.put(ip, this); // 加入set中
		addOnlineCount(); // 在线数加1
		log.info(ip + "加入！当前在线人数为" + getOnlineCount());
	}

  /**
   * 连接关闭调用的方法
   */
  @OnClose
  public void onClose() {
      webSocketSet.remove(this);  //从set中删除
      subOnlineCount();           //在线数减1
      log.info("有一连接关闭！当前在线人数为" + getOnlineCount());
  }

  /**
   * 收到客户端消息后调用的方法
   *
   * @param message 客户端发送过来的消息*/
  /*@OnMessage
  public void onMessage(String message, Session session) {
      log.info("来自客户端的消息:" + message);
      //可以自己约定字符串内容，比如 内容|0 表示信息群发，内容|X 表示信息发给id为X的用户
      String sendMessage = message.split("[|]")[0];
      String sendUserId = message.split("[|]")[1];
      try {
          if(sendUserId.equals("0"))
              sendtoAll(sendMessage);
          else
              sendtoUser(sendMessage,sendUserId);
      } catch (IOException e) {
          e.printStackTrace();
      }

  }*/

  /**
   *
   * @param session
   * @param error
   */
  @OnError
  public void onError(Session session, Throwable error) {
      log.error("发生错误");
      error.printStackTrace();
  }


  public void sendMessage(String message) throws IOException {
      this.session.getBasicRemote().sendText(message);
  }

  /**
   * 发送信息给指定ID用户，如果用户不在线则返回不在线信息给自己
   * @param message
   * @param sendUserId
   * @throws IOException
   */
  public void sendtoUser(String message,String sendFybm) throws IOException {   	
	  for(Map.Entry<String, WebSocketServer> entry: webSocketSet.entrySet()) {
		  String ip = entry.getKey();
		  List<UserInfo> list = userRepository.findByIp(ip);
		  if(list.size()>0) {
			  UserInfo userInfo = list.get(0);
			  if(containsFybm(sendFybm,userInfo.getFybm())) {
				  webSocketSet.get(ip).sendMessage(message);
			  }
		  }else {
			  System.out.println("发送失败，该IP地址不存在");
		  }
		  
		  
	  }
  }
  
  public static void main(String[] args) {
		// TODO Auto-generated method stu
		System.out.println(containsFybm("100;101;200;400","500"));

	}

  
  public static boolean containsFybm(String sendFybm,String fybm) {
	  String[] fybms = sendFybm.split(";");
	  boolean result = false;
	  for(int i=0;i<fybms.length;i++) {
		  if(fybms[i].equals(fybm)) {
			  result = true;
			  break;
		  }
	  }
	  return result;
  }

  /**
   * 发送信息给所有人
   * @param message
   * @throws IOException
   */
  public void sendtoAll(String message) throws IOException {
      for (String key : webSocketSet.keySet()) {
          try {
              webSocketSet.get(key).sendMessage(message);
          } catch (IOException e) {
              e.printStackTrace();
          }
      }
  }


  public static synchronized int getOnlineCount() {
      return onlineCount;
  }

  public static synchronized void addOnlineCount() {
      WebSocketServer.onlineCount++;
  }

  public static synchronized void subOnlineCount() {
      WebSocketServer.onlineCount--;
  }
}

